<?php

namespace App\V3\V3_2_7\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use OSS\OssClient;
use App\V3\V3_2_7\Models\SportIndexModel;
use App\V3\V3_2_7\Models\SportMenuModel;
use App\V3\V3_2_7\Models\SportQuestionModel;
use App\V3\V3_2_7\Services\SmsService;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;

/**
 * 户外运动网站
 * @author lf
 *
 */
class SportController extends Controller
{
    protected $ossClient;

    public function __construct(Request $request)
    {
        $this->ossClient = new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
        );
    }

    /**
     * 添加首页
     * @param Request $request
     */
    public function AddIndex(Request $request)
    {
        $data=$request->all();
        $data['created_at']=Carbon::now()->timestamp;
        $id = SportIndexModel::insertGetId($data);
        if($id){
            if (Cache::has('index')) {
                Cache::forget('index');
            }
            return success();
        }else{
            return fail('','添加失败');
        }
    }
    
    /**
     * 修改首页
     * @param Request $request
     */
    public function updIndex(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//库存id
        ],[
            'id.required'=>'要修改的菜单ID,不能为空',
            'id.integer'=>'要修改的菜单ID，必须为整数！',
        ]);
        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $info = SportIndexModel::where([
            'id' => $data['id'],
            'delete_flag' =>0
        ])->first();
        if(empty($info))
            return fail('','没有找到，要修改的首页信息');
        $id = $data['id'];
        unset($data['id']);
        $bool = SportIndexModel::where([
            'id' => $id,
            'delete_flag' =>0
        ])->update($data);
        if($bool){
            SELF::delIndexImg($data, $info, $this->ossClient);//删除oss存储的图片
            if (Cache::has('index')) {
                Cache::forget('index');
            }
            return success();
        }else{
            return fail('','修改失败');
        }
    }
    
    /**
     * 返回首页信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        $indexInfo = Cache::rememberForever('index', function(){
            $indexInfo = SportIndexModel::first();
            if(!empty($indexInfo)){
                if(!empty($indexInfo['image'])){
                    $indexInfo['image']=explode(',', $indexInfo['image']);
                }
                return $indexInfo;
            }
        });
       return success($indexInfo??[]);
    }
    
    /**
     * 添加菜单
     * @param Request $request
     */
    public function addMenu(Request $request)
    {
        $data=$request->all();
        $data['created_at']=Carbon::now()->timestamp;
        $id = SportMenuModel::insertGetId($data);
        if($id){
            if (Cache::has('menu_list')) {
                Cache::forget('menu_list');
            }
            return success();
        }else{
            return fail('','修改失败');
        }
    }
    
    /**
     * 修改菜单
     * @param Request $request
     */
    public function updMenu(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//库存id
            'nav_name'=> 'required',
        ],[
            'id.required'=>'要修改的菜单ID,不能为空',
            'id.integer'=>'要修改的菜单ID，必须为整数！',
            'nav_name.required'=>'菜单名称,不能为空',
        ]);
        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        $info = SportMenuModel::where([
            'id' => $data['id'],
            'delete_flag' =>0
        ])->first();
        if(empty($info))
            return fail('','没有找到，要修改的菜单信息');
        $delImg = [];
        if(isset($data['img']) && $info['img']){
            $imgArr = explode(',', $info['img']);
            $reqImgArr = explode(',', $data['img']);
            $collection = collect($imgArr);
            $delImg = $collection->diff($reqImgArr);
            $delImg->all();
            
        }
        $id=$data['id'];
        unset($data['id']);
        $bool = SportMenuModel::where([
            'id' => $id,
            'delete_flag' =>0
        ])->update($data);
        if($bool){
            SELF::delMenuImg($this->ossClient,$delImg);
            if (Cache::has('menu_list')) {
                Cache::forget('menu_list');
            }
            return success();
        }else{
            return fail('','修改失败');
        }
    }
    
    /**
     * 删除菜单
     * @param Request $request
     */
    public function delMenu(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//菜单id
        ],[
            'id.required'=>'要修改的菜单ID,不能为空',
            'id.integer'=>'要修改的菜单ID，必须为整数！',
            'nav_name.required'=>'菜单名称,不能为空',
        ]);
        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        $info = SportMenuModel::where([
            'id' => $data['id'],
            'delete_flag' =>0
        ])->first();
        if(empty($info))
            return fail('','没有找到，要删除的菜单信息');
        $id = $data['id'];
        unset($data['id']);
        $bool = SportMenuModel::where([
            'id' => $id,
            'delete_flag' =>0
        ])->update(['delete_flag'=>1]);
        if($bool){
            $subMenuList = SportMenuModel::where([
                'parent_id' => $info['id'],
                'delete_flag' =>0
            ])->get()->toArray();
            if(!empty($subMenuList)){
                foreach ($subMenuList as $subVal){
                    SportMenuModel::where([
                        'id' => $subVal['id'],
                        'delete_flag' =>0
                    ])->update(['delete_flag'=>1]);
                    SELF::delMenuImg($this->ossClient,$subVal['img']);
                }
            }
            SELF::delMenuImg($this->ossClient,$info['img']);
            if (Cache::has('menu_list')) {
                Cache::forget('menu_list');
            }
            return success();
        }else{
            return fail('','删除失败');
        }
    }
    
    /**
     * 菜单列表
     * @param Request $request
     */
    public function menuList(Request $request)
    { 
        $menuList = Cache::rememberForever('menu_list', function(){
            $menuList = SportMenuModel::select('id','nav_name','img','sort')
            ->from('sport_menu')
            ->where('parent_id',0)
            ->where('delete_flag',0)
            ->orderBy('sort','asc')
            ->orderBy('created_at','asc')
            ->get()->toArray();
            if(!empty($menuList)){
                foreach ($menuList as &$val){
                    if(!empty($val['img'])){
                        $val['img'] = explode(',', $val['img']);
                    }
                    $val['sub_menu'] = SportMenuModel::select('id','nav_name','img','sort')
                    ->from('sport_menu')
                    ->where('parent_id',$val['id'])
                    ->where('delete_flag',0)
                    ->orderBy('sort','asc')
                    ->orderBy('created_at','asc')
                    ->get()->toArray();
                    if(!empty($val['sub_menu'])){
                        foreach ($val['sub_menu'] as &$item){
                            if(!empty($item['img'])){
                                $item['img'] = explode(',', $item['img']);
                            }
                        }
                    }
                }
            }
            return $menuList??[];
        });
        return success($menuList);
    }
    //发送验证码
    public function sendCode(Request $request)
    {
        $result = self::checkMobile($request->all());//校验手机号
        if($result == '') {
            if(Redis::exists($request->mobile.'_question')) {
                return ['code' => 1, 'msg' => '验证码已发送，请勿重新点击', 'data' => ''];
            }
            return response()->json(SmsService::sportSendCode($request->mobile));
        }else {
            return response()->json([
                'code' => 1,
                'msg' => $result,
                'data' => ''
            ]);
        }
    }
    
    /**
     * 添加咨询
     * @param Request $request
     */
    public function addQuestion(Request $request)
    {
        $data = $request->all();
        $data['created_at'] = Carbon::now()->timestamp;
        
        //比对用户输入的code和短信发送的code是否一致
        if(!Redis::exists($data['mobile'].'_question')) {
            return ['code' => 1, 'msg' => '您输入的验证码无效，请重试', 'data' => ''];
        }else {
            
            if($data['code'] == Redis::get($data['mobile'].'_question')) {//验证码一致
                unset($data['code']);
                $id = SportQuestionModel::insertGetId($data);
                if($id){
                    if (Cache::has('question_list')) {
                        Cache::forget('question_list');
                    }
                    return success();
                }
            }else{
                return fail('','您输入的验证码有误，请重新发送！');
            }
        }
        return fail('','添加失败');
    }
    
    /**
     * 审核咨询
     * @param Request $request
     */
    public function updQuestion(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//库存id
        ],[
            'id.required'=>'审核咨询ID,不能为空',
            'id.integer'=>'审核咨询ID，必须为整数！',
        ]);
        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $bool = SportQuestionModel::where([
            'id' => $data['id'],
            'check' =>0
        ])->update(['check'=>1]);
        if($bool){
            if (Cache::has('question_list')) {
                Cache::forget('question_list');
            }
            return success();
        }else{
            return fail('','审核失败');
        }
    }
    
    /**
     * 咨询列表
     * @param Request $request
     */
    public function questionList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);
        
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return fail('', $info);
        }
        $list = Cache::rememberForever('question_list', function() use($data){
            return SportQuestionModel::select('*')
            ->orderBy('check','asc')
            ->orderBy('created_at','desc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);
        });
        return success($list);
    }
    
    //校验手机号
    private function checkMobile($data) {
        $messages = [
            'mobile.required' => '手机号不能为空，请输入手机号',
            'mobile.regex' => '手机号格式错误，请重试',
        ];
        
        $validator = Validator::make($data, [
            'mobile' => 'required|regex:/^1[3456789][0-9]{9}$/',
        ], $messages);
        
        return $validator->errors()->first();
    }
    
    
    /**
     * 图片上传
     * @param Request $request
     * 2023/9/23 10:09
     * Author: zlf
     * @return array|\Illuminate\Http\JsonResponse|string[]
     */
    public function upload(Request $request)
    {
        $files = $request->file('images');
        if(empty($files)) {
            return $this->fail('', '请选择图片');
        }
        
        $fileSize = $files->getSize();
        
        if($fileSize > 2097152) {
            //return ['code' => 1, 'msg' => '图片大小不能超出2M', 'data' => ''];
            return $this->fail('', '图片大小不能超出2M');
        }
        
        if(!in_array($files->extension(), ['jpg', 'jpeg', 'png'])) {
            //return ['code' => '1', '不支持的图片格式，当前仅支持`png`和`jpg`以及`jpeg`', 'data' => ''];
            return $this->fail('', '不支持的图片格式，当前仅支持`png`和`jpg`以及`jpeg`');
        }
        
        $uploadPath = $files->store(date('Y').'/'.date('m').'/'.date('d'));
        
        $fullPath = '/uploads/'.$uploadPath;
        $ossPath = ltrim($fullPath, './');
        $path = public_path().$fullPath;
       
        $client = $this->ossClient;
        /**
         * @param $ossPath oss服务器路径
         * @param $path 服务器图片绝对路径
         * @param config('app.aliyun_oss_bucket') 目标bucket
         */
        $client->uploadFile(config('app.aliyun_oss_bucket'),  $ossPath, $path);
        
        //删除服务器上传后存储的图片
        unlink($path);
        
        return success(config('app.aliyun_oss_bucket_url').$fullPath);
    }
    
    /**
     * 删除首页oss存储的图片
     * @param unknown $ReqImg
     * @param unknown $baseImg
     * @return \Illuminate\Support\Collection
     */
    static public function delIndexImg($data,$info,$ossClient){
       foreach ($data as $key => $val){
           if(in_array($key, ['image','logo','weixin','douyin'])){
               if(isset($data[$key]) && !empty($info[$key])){
                   $imgArr = explode(',', $info[$key]);
                   $reqImgArr = explode(',', $data[$key]);
                   $collection = collect($imgArr);
                   $delImg = $collection->diff($reqImgArr);
                   $delImg->all();
                   SELF::delMenuImg($ossClient,$delImg);
               }
           }
       }
    }
   
    /**
     * 删除菜单oss存储的图片
     * @param unknown $ReqImg
     * @param unknown $baseImg
     * @return \Illuminate\Support\Collection
     */
    static public function delMenuImg($ossClient,$delImg){
        if(!empty($delImg)){
            if(is_array($delImg)){
                foreach ($delImg as $dVal){
                    $substrUrl = explode('uploads', $dVal);
                    $ossClient->deleteObject(config('app.aliyun_oss_bucket'), 'uploads'.$substrUrl[1]);
                
                }
            }else{
                $substrUrl = explode('uploads', $delImg);
                $ossClient->deleteObject(config('app.aliyun_oss_bucket'), 'uploads'.$delImg);
            }
        }
    }
    /**
     * 清除所有缓存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delCache(Request $request){
        if (Cache::has('index')) {
            Cache::forget('index');
        }
        
        if (Cache::has('menu_list')) {
            Cache::forget('menu_list');
        }
        
        if (Cache::has('question_list')) {
            Cache::forget('question_list');
        }
        return success();
    }
}
